import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonResponse {
    public JsonResponse() {
        this.properties = new HashMap<>();
    }

    public void addProperty(String key, Object value) {
        properties.put(key, value);
    }

    public Object getProperty(String key) {
        return properties.get(key);
    }

    public String getPropertyString(String key) {
        Object value = properties.get(key);
        return value != null ? value.toString() : null;
    }

    @Override
    public String toString() {
        String json;
        try {
            json = JsonResponse.mapper.writeValueAsString(properties);
        } catch (JsonProcessingException e) {
            json = null;
            throw new RuntimeException(e);
        }
        return json;
    }

    public static JsonResponse parse(String json) {
        Map<String, Object> res;
        JsonResponse result = new JsonResponse();
        if (json == null || json.trim().isEmpty()) {
            return result;
        }
        try {
            res = JsonResponse.mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {});
            result.properties = res;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    private static ObjectMapper mapper = new ObjectMapper();

    public Map<String, Object> getProperties() {
        return properties;
    }

    private Map<String, Object> properties;
}
